package com.eastsunsoft.swordfish.cms.service.impl;

import com.eastsunsoft.swordfish.cms.entity.CmsArticle;
import com.eastsunsoft.swordfish.cms.mapper.CmsArticleMapper;
import com.eastsunsoft.swordfish.cms.service.CmsArticleService;
import com.eastsunsoft.swordfish.common.ApiConstant;
import com.eastsunsoft.swordfish.common.SwordfishException;
import com.eastsunsoft.swordfish.common.event.SfEventOutCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <h1>CmsArticleServiceImpl</h1>
 * </br>
 *
 * @author donny
 * @date 20/09/2017
 */
@Service
@Transactional
public class CmsArticleServiceImpl implements CmsArticleService {
    @Autowired
    private CmsArticleMapper cmsArticleMapper;

    @Autowired
    @Qualifier(SfEventOutCommon.OUT_COMMON)
    private MessageChannel output;


    @Override
    public void save(CmsArticle article) {
        cmsArticleMapper.insertSelective(article);

        System.out.println(Thread.currentThread().getName());
//        List<CmsArticle> articles = new ArrayList<>();
//        articles.add(article);
//        CmsArticle article1 = new CmsArticle();
//        article1.setId(2L);
//        article1.setTitle("abc中国");
//        articles.add(article1);

        try {
            if (!output.send(MessageBuilder.withPayload(article).build())) {
                throw new SwordfishException(ApiConstant.ERRCODE_500);
            }
        } catch (Exception e) {
            throw new SwordfishException(ApiConstant.ERRCODE_500);
        }
//        TransactionSynchronizationManager.registerSynchronization(
//                new TransactionSynchronizationAdapter() {
//                    @Override
//                    public void afterCommit() {
//                        System.out.println(Thread.currentThread().getName());
//                        cmsEventService.sendEvent(article);
//                    }
//                }
//        );
//        if (true) {
//            throw new SwordfishException(ApiConstant.ERRCODE_500);
//        }
    }
}
